// 1. 常量定义（分类配置、存储键名）
const CATEGORY_CONFIG = {
  income: [
    { value: "salary", label: "工资" },
    { value: "part-time", label: "兼职" },
    { value: "red-packet", label: "红包" },
    { value: "investment", label: "投资收益" },
    { value: "other-income", label: "其他收入" }
  ],
  expense: [
    { value: "food", label: "餐饮" },
    { value: "transport", label: "交通" },
    { value: "shopping", label: "购物" },
    { value: "entertainment", label: "娱乐" },
    { value: "other-expense", label: "其他支出" }
  ]
};
const STORAGE_KEY = "budgetRecords";

// 2. 页面初始化（加载时执行）
function init() {
  // 设置默认日期为当天
  const today = new Date().toISOString().split("T")[0];
  document.getElementById("recordDate").value = today;

  // 监听类型选择变化，动态切换分类
  document.getElementById("recordType").addEventListener("change", handleTypeChange);

  // 监听表单提交，添加记录
  document.getElementById("budgetForm").addEventListener("submit", handleFormSubmit);

  // 加载本地数据并渲染
  renderAllData();
}

// 3. 表单处理：类型切换、提交验证
function handleTypeChange() {
  const type = document.getElementById("recordType").value;
  const categorySelect = document.getElementById("category");
  categorySelect.innerHTML = "";

  if (!type) {
    categorySelect.innerHTML = '<option value="">请先选择类型</option>';
    return;
  }

  // 生成对应分类选项
  CATEGORY_CONFIG[type].forEach(item => {
    const option = document.createElement("option");
    option.value = item.value;
    option.textContent = item.label;
    categorySelect.appendChild(option);
  });
}

function handleFormSubmit(e) {
  e.preventDefault();
  // 获取表单值
  const type = document.getElementById("recordType").value;
  const amount = parseFloat(document.getElementById("amount").value);
  const category = document.getElementById("category").value;
  const date = document.getElementById("recordDate").value;
  const remark = document.getElementById("remark").value.trim() || "无";

  // 表单验证
  if (!type || !amount || !category || !date) {
    alert("请填写所有必填项！");
    return;
  }
  if (isNaN(amount) || amount < 0) {
    alert("金额必须是非负数字！");
    document.getElementById("amount").focus();
    return;
  }

  // 构造记录对象
  const newRecord = {
    id: Date.now().toString(),
    type,
    amount,
    category,
    date,
    remark
  };

  // 保存到本地存储
  saveRecord(newRecord);
  // 重置表单
  document.getElementById("budgetForm").reset();
  handleTypeChange();
  document.getElementById("recordDate").value = new Date().toISOString().split("T")[0];
  // 重新渲染
  renderAllData();
  alert("记录添加成功！");
}

// 4. 本地存储：获取、保存、删除
function getRecords() {
  const recordsStr = localStorage.getItem(STORAGE_KEY);
  return recordsStr ? JSON.parse(recordsStr) : [];
}

function saveRecord(record) {
  const records = getRecords();
  records.push(record);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
}

function deleteRecord(id) {
  let records = getRecords();
  records = records.filter(item => item.id !== id);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
}

// 5. 数据渲染：表格、统计
function renderAllData() {
  const records = getRecords();
  renderRecordsTable(records);
  renderStats(records);
}

function renderRecordsTable(records) {
  const tbody = document.getElementById("recordsBody");
  tbody.innerHTML = "";

  if (records.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" class="empty-records">暂无收支记录，请添加第一条记录</td></tr>';
    return;
  }

  // 按日期倒序排列（最新在前）
  const sortedRecords = [...records].sort((a, b) => new Date(b.date) - new Date(a.date));

  // 生成表格行
  sortedRecords.forEach(record => {
    const tr = document.createElement("tr");
    const typeText = record.type === "income" ? "收入" : "支出";
    const typeClass = record.type === "income" ? "record-type-income" : "record-type-expense";
    const categoryLabel = getCategoryLabel(record.type, record.category);

    tr.innerHTML = `
      <td><span class="${typeClass}">${typeText}</span></td>
      <td>¥${record.amount.toFixed(2)}</td>
      <td>${categoryLabel}</td>
      <td>${record.date}</td>
      <td>${record.remark}</td>
      <td><button class="delete-btn" data-id="${record.id}">删除</button></td>
    `;
    tbody.appendChild(tr);
  });

  // 绑定删除事件
  document.querySelectorAll(".delete-btn").forEach(btn => {
    btn.addEventListener("click", () => {
      if (confirm("确定删除这条记录吗？删除后无法恢复！")) {
        deleteRecord(btn.dataset.id);
        renderAllData();
      }
    });
  });
}

function renderStats(records) {
  // 计算总收入、总支出、余额
  let totalIncome = 0, totalExpense = 0;
  records.forEach(item => {
    item.type === "income" ? totalIncome += item.amount : totalExpense += item.amount;
  });
  const totalBalance = totalIncome - totalExpense;

  // 渲染基础统计
  document.getElementById("totalIncome").textContent = `¥${totalIncome.toFixed(2)}`;
  document.getElementById("totalExpense").textContent = `¥${totalExpense.toFixed(2)}`;
  const balanceElem = document.getElementById("totalBalance");
  balanceElem.textContent = `¥${totalBalance.toFixed(2)}`;
  balanceElem.className = `stat-value ${totalBalance > 0 ? "income" : totalBalance < 0 ? "expense" : ""}`;

  // 渲染支出分类占比
  const progressContainer = document.getElementById("categoryProgressContainer");
  if (totalExpense === 0) {
    progressContainer.innerHTML = '<p class="empty-tip">暂无支出数据</p>';
    return;
  }

  // 计算各支出分类总额
  const expenseCategoryTotal = {};
  records.forEach(item => {
    if (item.type === "expense") {
      expenseCategoryTotal[item.category] = (expenseCategoryTotal[item.category] || 0) + item.amount;
    }
  });

  // 生成进度条HTML
  let progressHTML = "";
  Object.entries(expenseCategoryTotal).forEach(([key, value]) => {
    const percentage = ((value / totalExpense) * 100).toFixed(1);
    const label = getCategoryLabel("expense", key);
    progressHTML += `
      <div class="category-progress category-${key}">
        <div class="progress-label">
          <span>${label}</span>
          <span>¥${value.toFixed(2)} (${percentage}%)</span>
        </div>
        <div class="progress-bar">
          <div class="progress-fill" style="width: ${percentage}%"></div>
        </div>
      </div>
    `;
  });
  progressContainer.innerHTML = progressHTML;
}

// 辅助函数：获取分类中文标签
function getCategoryLabel(type, value) {
  const category = CATEGORY_CONFIG[type].find(item => item.value === value);
  return category ? category.label : "未知分类";
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", init);